# -*- coding: utf8 -*-
__author__ = 'Sergey Dryabzhinsky'

__doc__ = """
Process images with ImageMagick (PythonMagick)

@author: Sergey Dryabzhinsky
"""

import math
import PythonMagick
from logger import get_file_logger
from multiprocessing import current_process
from threading import current_thread


class iMagick(object):

    filename = None

    img = None

    log = None

    def get_logger(self):
        if self.log is None:
            self.log = get_file_logger(self.__class__.__name__ + "[%s-%s]" % (current_process().pid, current_thread().getName()))
        return self.log

    def is_image(self, filename):
        is_img = False
        try:
            img = self.load(filename)
            is_img = img is not None
            if is_img:
                is_img = img.isValid()
        except Exception as e:
            pass
        self.close()
        return is_img

    def close(self):
        if self.img:
            self.img = None
            self.filename = None
        return self

    def load(self, filename):
        self.img = PythonMagick.Image(filename.encode('utf-8'))
        # len(self.img.data)
        return self.img

    def width(self):
        if self.img:
            return self.img.columns()
        return 0

    def height(self):
        if self.img:
            return self.img.rows()
        return 0


    def process_image(self, mirror=False, parts=100):
        """
        Process image data and calculate some results

        @return:    calculated data:
                    {
                        "color" : bool,
                        "mean_gray" : int,
                        "vector" : list
                    }
        @rtype:     dict
        """

        result = {
            "color": False,
            "mean_gray": 0,
            "vector": None
        }

        img = self.img

        if mirror:
            img = img.flip()

        vector = {}.fromkeys(range(parts), 0)

        geom = img.size()

        w = geom.width()
        h = geom.height()

        if w == 0 or h == 0:
            w = img.columns()
            h = img.rows()

        if w == 0 or h == 0:
            vector = range(parts)
            vector = list(map(lambda item: 0, vector))
            result["vector"] = tuple(vector)
            return result

        vw = math.sqrt(float(w) / float(h) * parts)
        vh = math.sqrt(float(h) / float(w) * parts)

        # resample for bicubic
        rsw = int( math.ceil(vw) ) * 4
        rsh = int( math.ceil(vh) ) * 4

        img.sample( "!%sx%s" % (rsw, rsh) )

        wr = range(rsw)
        hr = range(rsh)

        meanColor = 0

        for x in wr:
            for y in hr:

                color = img.pixelColor(x, y)

                r = color.redQuantum()
                g = color.greenQuantum()
                b = color.blueQuantum()

                r = color.scaleQuantumToDouble(r)
                g = color.scaleQuantumToDouble(g)
                b = color.scaleQuantumToDouble(b)

                r = int(r * 255)
                g = int(g * 255)
                b = int(b * 255)

                Y = 0.5 * (max((r, g, b,)) + min((r, g, b,)))

                if r != g or g != b:
                    result["color"] = True

                vn = int(math.floor(float(x * rsh + y) / float(rsw * rsh) * (vw * vh)))

                if vector.get(vn, 0) == 0:
                    vector[vn] = {
                        "c": 0,
                        "n": 0
                    }
                vector[vn]["c"] += Y
                vector[vn]["n"] += 1

                meanColor += Y

        meanColor /= rsw * rsh
        result["mean_gray"] = int(meanColor)

        rv = ()
        for key in range(parts):
            item = vector.get(key)
            if not item or not item["n"]:
                rv += (0,)
            else:
                rv += (int(item["c"] * 1.0 / item["n"]),)

        result["vector"] = rv
        return result

